package com.alibaba.cloud.config;

import org.axonframework.commandhandling.SimpleCommandBus;
import org.axonframework.config.SagaConfiguration;
import org.axonframework.config.SagaConfigurer;
import org.axonframework.eventhandling.EventBus;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.spring.config.AxonConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.cloud.application.BankAccountCommandHandler;
import com.alibaba.cloud.application.BankTransferManagementSaga;
import com.alibaba.cloud.domain.BankAccountDomain;

import lombok.RequiredArgsConstructor;

@Configuration
@RequiredArgsConstructor
public class AxonConfig {
	private final AxonConfiguration axonConfiguration;
	private final EventBus eventBus;

	@Bean
	public BankAccountCommandHandler bankAccountCommandHandler() {
		return new BankAccountCommandHandler(axonConfiguration.repository(BankAccountDomain.class), eventBus);
	}

	@Bean
	public SagaConfiguration<BankTransferManagementSaga> sagaConfiguration() {
		return SagaConfigurer.forType(BankTransferManagementSaga.class).initialize(axonConfiguration);
	}

	@Autowired
	public void configure(@Qualifier("localSegment") SimpleCommandBus simpleCommandBus) {
		simpleCommandBus.registerDispatchInterceptor(new BeanValidationInterceptor<>());
	}
}
